package com.caregiver.watch.business.data.utils;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

@Slf4j
public final class HttpHelper {

    public static void printHeaders(HttpServletRequest request) {
        StringBuilder headerInfo = new StringBuilder();
        // Get all header names
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headerInfo.append(headerName).append(": ");
            // Get all values for the current header
            Enumeration<String> headerValues = request.getHeaders(headerName);
            while (headerValues.hasMoreElements()) {
                headerInfo.append(headerValues.nextElement());
                if (headerValues.hasMoreElements()) {
                    headerInfo.append(", "); // If there are multiple values, separate them with a comma
                }
            }

            headerInfo.append("\n");
        }
        log.info(headerInfo.toString());
    }


    /**
     * Write data to the response
     *
     * @param resp
     * @param data
     */
    public static <T> void write(HttpServletResponse resp, T data) {
        try (ServletOutputStream outputStream = resp.getOutputStream()) {
            JSON.writeTo(outputStream, data);
        } catch (Exception e) {
            log.error("Error writing response: {}", e.getMessage());
        }
    }
}
